<template>
  <el-card>
    <el-button type="primary" size="default" icon="plus" @click="addTrade">添加品牌</el-button>
    <el-table border stripe :data="tradeList" style="margin: 10px 0">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌logo">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <el-button type="warning" size="small" icon="edit" @click="editTrade(row)"></el-button>
          <el-popconfirm :title="`你要的要删除${row.tmName}吗？`" @confirm="deleteTrade(row.id)">
            <template #reference>
              <el-button type="danger" size="small" icon="delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="changeSize"
      @current-change="changeCurrent"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :background="true"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="totalNum"
      :page-sizes="[3, 6, 9, 10]"
    />
  </el-card>
  <el-dialog v-model="dialogFormVisible" :title="tradeForm.id ? '修改品牌' : '添加品牌'">
    <el-form :model="tradeForm" :rules="rules" ref="tradeforms">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="tradeForm.tmName" />
      </el-form-item>
      <el-form-item label="品牌logo" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:5173/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="tradeForm.logoUrl" :src="tradeForm.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmTrade">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reqAddOrUpdateTrade, reqDeleteTrade, reqGetTradeList } from '@/api/peoduct/trademark'
import type { Records, tradeMark, tradeMarkRes } from '@/api/peoduct/trademark/type'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type UploadProps } from 'element-plus'
let currentPage = ref<number>(1)
let pageSize = ref<number>(3)
let totalNum = ref<number>(30)
let tradeList = ref<Records>([])
let dialogFormVisible = ref<boolean>(false)
let tradeforms = ref()
const getTradeList = async (pager = 1) => {
  currentPage.value = pager
  let res: tradeMarkRes = await reqGetTradeList(currentPage.value, pageSize.value)
  if (res.code == 200) {
    totalNum.value = res.data.total
    tradeList.value = res.data.records
  }
}
let tradeForm = reactive<tradeMark>({
  tmName: '',
  logoUrl: '',
})
const changeSize = () => {
  getTradeList()
}
const changeCurrent = (num: number) => {
  getTradeList(num)
}

onMounted(() => {
  getTradeList()
})

const addTrade = () => {
  dialogFormVisible.value = true
  Object.assign(tradeForm, { tmName: '', logoUrl: '', id: '' })
  tradeforms.value?.clearValidate('logoUrl')
  tradeforms.value?.clearValidate('tmName')
}
const editTrade = (row: object) => {
  dialogFormVisible.value = true
  Object.assign(tradeForm, row)
  tradeforms.value?.clearValidate('logoUrl')
  tradeforms.value?.clearValidate('tmName')
}
const deleteTrade = async (id:number) => {
  let res:any = await reqDeleteTrade(id)
  if(res.code == 200) {
    ElMessage({
      type:'success',
      message : '删除成功'
    })
    getTradeList(tradeList.value.length < 1 ? currentPage.value - 1 : currentPage.value)
  }else {
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }
}
const confirmTrade = async () => {
  await tradeforms.value.validate()
  dialogFormVisible.value = false
  const res: any = await reqAddOrUpdateTrade(tradeForm)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: `${tradeForm.id ? '修改' : '添加'}品牌成功`,
    })
    getTradeList(tradeForm.id ? currentPage.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: `${tradeForm.id ? '修改' : '添加'}品牌失败`,
    })
  }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('请上传正确的类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('所传图片不能超过2MB!')
    return false
  }
  return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  tradeForm.logoUrl = response.data
  tradeforms.value.clearValidate('logoUrl')
}
const validataTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌长度不足2位'))
  }
}
const validatalogoUrl = (rule: any, value: any, callback: any) => {
  if (value.trim() == '') {
    callback(new Error('请上传logo'))
  } else {
    callback()
  }
}
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validataTmName }],
  logoUrl: [{ required: true, validator: validatalogoUrl }],
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
